package com.teapos.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.teapos.enumtype.CustomerTypeEnum;
import com.teapos.service.CustomerService;
import com.teapos.service.ScatService;
import com.teapos.service.UserService;
import com.teapos.util.Lists;
import com.teapos.util.Maps;
import com.teapos.util.Tool;

/**
 * 散客controller
 * @author kangrui
 *
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@RequestMapping("/scat")
@Controller
public class ScatteredController extends BaseController {
	
	public static final String TMEP_CODE = "123456";
	
	@Autowired
	private ScatService scatService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	
	@RequestMapping("/index")
	public String index() {
		return "scat/index";
	}
	
	/**
	 * 扫描二维码对应商品
	 * @param req
	 * @param res
	 * @param code
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/scan")
	public String scanQRcode(HttpServletRequest req, HttpServletResponse res, String code) {
		Cookie cookie = Tool.getCookie(req, SHOP_CART);
		Tool.printCookie(req);
		int role = Tool.toInt(super.getUser(req).get("role"));
		System.err.println(role);
		Map qrcode = scatService.findQRcode(code, role);
		if(qrcode==null) return fail("没有找到商品！！");
		Map map = Maps.newHashMap("product", qrcode);
		if(cookie==null) {
			cookie = new Cookie(SHOP_CART, code);
			cookie.setPath("/");
			res.addCookie(cookie);
			return success(null, map);
		} else {
			String codes = cookie.getValue();
			System.err.println("code="+code+",codes="+codes);
			if(codes.indexOf(code)==-1) {
				cookie.setValue(cookie.getValue()+"&"+code);
				cookie.setPath("/");
				res.addCookie(cookie);
				return success(null, map);
			} else {
				return fail("该商品已经扫描过！");
			}
		}
	}
	
	@RequestMapping("/next")
	public String next(Map map, HttpServletRequest req) {
		map.put("customertypes", CustomerTypeEnum.values());
		Map user = super.getUser(req);
		int role = Tool.toInt(user.get("role"));
		map.put("saveDiscount", userService.findUserSaveDiscounts(role));
		return "scat/next";
	}
	
	@ResponseBody
	@RequestMapping("/findcustomer")
	public String findcustomer(String name, String tel) {
		return JSON.toJSONString(customerService.queryCustomers(name, tel));
	}
	
	@ResponseBody
	@RequestMapping("/addCustomer")
	public String addCustomer(HttpServletRequest req) {
		try {
			int id = customerService.addCustomer(Maps.put(getParaMap(req), "uid", getUserId(req)));
			return success("添加成功！！", Maps.newHashMap("id", id));
		} catch (Exception e) {
			e.printStackTrace();
			return fail("添加失败！！");
		}
	}
	
	@ResponseBody
	@RequestMapping("/loadCookie")
	public String loadCookie(HttpServletRequest req) {
		String[] codes = req.getParameter("codes").replaceAll("&&", "&").split("&");
		String discounts = Tool.getCookieValue(req, "back_discounts");
		List discountList = JSON.parseArray(discounts);
		Map discountMap = new HashMap();
		if(!CollectionUtils.isEmpty(discountList)) {
			Iterator iter = discountList.iterator();
			while(iter.hasNext()) {
				Map discount = (Map) iter.next();
				discountMap.put(discount.get("key"), discount.get("value"));
			}
		}
		int role = Tool.toInt(super.getUser(req).get("role"));
		List products = Lists.newArrayList();
		for(String code:codes) {
			if(StringUtils.isNotBlank(code)) {
				Map product = scatService.findQRcode(code.replaceAll("&", ""), role);
				Object discount = discountMap.get(code);
				product.put("discount", discount==null?1:discount);
				products.add(product);
			}
		}
		return JSON.toJSONString(products);
	}
	
	@RequestMapping("/pay")
	public String pay() {
		return "pay";
	}

	@RequestMapping("/findProduct")
	public String findProduct(String info, ModelMap model) {
		model.addAttribute("products", scatService.findTop10Products(info));
		return "scat/product_table";
	}
	
	@ResponseBody
	@RequestMapping("/temp_scan")
	public String tempScan(HttpServletRequest req, HttpServletResponse res) {
		String tempCode = scatService.findTempCode(Tool.toString(super.getUser(req).get("stid")));
		if(!req.getParameter("temp").equals(tempCode)) return fail("临时二维码有误！！");
		Cookie cookie = Tool.getCookie(req, SHOP_CART);
		Map param = super.getParaMap(req);
		String codes = null;
		if(cookie!=null) {
			codes = cookie.getValue();
			String[] codeArr = codes.split("&");
			List codeList = Arrays.asList(codeArr);
			param.put("codes", codeList);
		}
		
		param.put("role", super.getUser(req).get("role"));
		Map codeMap = scatService.findQRcodeByProductId(param);
		if(codeMap==null) return fail("没有查询到商品！！");
		Map map = Maps.newHashMap("product", codeMap);
		String code = Tool.toString(codeMap.get("code"));
		if(cookie==null) {
			cookie = new Cookie(SHOP_CART, code);
			cookie.setPath("/");
			res.addCookie(cookie);
			return success(null, map);
		} else {
			cookie.setValue(cookie.getValue()+"&"+code);
			cookie.setPath("/");
			res.addCookie(cookie);
			return success(null, map);
		}
	}
	
	@RequestMapping("/find_unit")
	public String findUnit(String id, Map map) {
		map.put("units", scatService.findUnitByPid(id));
		return "scat/unit";
	}
	
}
